package cz.proks.schoolpupilbook.gae.converter;

import com.google.appengine.api.datastore.KeyFactory;

import cz.proks.schoolpupilbook.gae.dao.CourseDAO;
import cz.proks.schoolpupilbook.gae.dao.UserDAO;
import cz.proks.schoolpupilbook.gae.dbo.MarkCommentDBO;
import cz.proks.schoolpupilbook.gae.dbo.MarkDBO;
import cz.proks.schoolpupilbook.shared.domain.Course;
import cz.proks.schoolpupilbook.shared.domain.Mark;
import cz.proks.schoolpupilbook.shared.domain.MarkComment;
import cz.proks.schoolpupilbook.shared.domain.User;
import cz.proks.schoolpupilbook.shared.util.Tester;

public class MarkCommentConverter implements Converter<MarkCommentDBO, MarkComment>{
	@Override
	public MarkCommentDBO getDBO(MarkComment domain) {
		if (domain == null)
			return null;
		
		MarkCommentDBO dbo = new MarkCommentDBO();
		
		if (!Tester.isEmpty(domain.getId()))
			dbo.setId(KeyFactory.stringToKey(domain.getId()));
		
		Mark mark = domain.getMark();
		MarkDBO markDBO = new MarkDBO();		
		markDBO.setId(KeyFactory.stringToKey(mark.getId()));		
				
		dbo.setTime(domain.getTime());
		dbo.setMark(markDBO);
		dbo.setContributorKey(KeyFactory.stringToKey(domain.getContributor().getId()));
		dbo.setComment(domain.getComment());
		
		return dbo;
	}

	@Override
	public MarkComment getDomain(MarkCommentDBO dbo) {
		if (dbo == null)
			return null;
		
		MarkComment domain = new MarkComment();
		MarkDBO markDBO = dbo.getMark();
		
		UserDAO userDao = new UserDAO();
		CourseDAO courseDao = new CourseDAO();
		
		User student = userDao.find(markDBO.getStudentKey());
		User lector = userDao.find(markDBO.getLectorKey());
		Course course = courseDao.find(markDBO.getCourseKey());
				
		Mark mark = new Mark(KeyFactory.keyToString(markDBO.getId()), lector, student, course, markDBO.getTime(), markDBO.getGrade());
		User contributor = userDao.find(dbo.getContributorKey());
				
		domain.setId(KeyFactory.keyToString(dbo.getId()));
		domain.setTime(dbo.getTime());
		domain.setMark(mark);
		domain.setContributor(contributor);
		domain.setComment(dbo.getComment());
		
		return domain;
	}
}
